// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import store from './store'

var axios=require('axios')
axios.defaults.baseURL='http://localhost:8443/api'
Vue.prototype.$axios=axios

Vue.config.productionTip = false

Vue.use(ElementUI)

router.beforeEach((to,from,next) =>{
 // console.log(store.state.adminMenus)
  if(store.state.username &&to.path.startsWith('/admin')){
    console.log("进啦")
    initAdminMenu(router,store)
  }
  if (store.state.username && to.path.startsWith('/login')) {
    next({
      name: 'Welcome'
    })
  }
  if (to.meta.requireAuth) {
    if (store.state.username) {
      next()
    } else {
      console.log("username没有了")
      next({
        path: 'login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

const initAdminMenu=(router,store) =>{
  
  if(store.state.adminMenus.length>0){
    console.log("菜单长度大于0 直接返回")
    return
  }
//  console.log(store.state.username)
console.log("发送获取menu请求")
console.log(store.state.radio)
  axios.get('/menu',{
    params:{
      username:store.state.username,
      radio:store.state.radio
    }
  }).then(resp =>{
    if(resp&&resp.status===200){
      //console.log(resp.data)
      var fmtRoutes=formatRoutes(resp.data.result)
      router.addRoutes(fmtRoutes)
      console.log(fmtRoutes)
      store.commit('initAdminMenu',fmtRoutes)
    }
  })
}


const formatRoutes = (routes) => {
  let fmtRoutes = []
  routes.forEach(route => {
    if (route.children) {
      route.children = formatRoutes(route.children)
    }

    let fmtRoute = {
      path: route.path,
      component: resolve => {
        require(['./components/admin/' + route.component + '.vue'], resolve)
      },
      name: route.name,
      nameZh: route.nameZh,
      iconCls: route.iconCls,
      meta: {
        requireAuth: true
      },
      children: route.children
    }
    fmtRoutes.push(fmtRoute)
  })
  return fmtRoutes
}



/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  store,
  template: '<App/>'
})
